package pe.com.itworth.ttsclient.controller;

import java.util.ArrayList;
import java.util.Collection;

import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;

import pe.com.itworth.ttsclient.infrastructure.MailManager;
import pe.com.itworth.ttsclient.infrastructure.MailMannagerGMAILImpl;
import pe.com.itworth.ttsclient.infrastructure.MailReaderJavaMailImpl;
import pe.com.itworth.ttsclient.infrastructure.Parser;
import pe.com.itworth.ttsclient.infrastructure.ParserGSON;
import pe.com.itworth.ttsclient.shared.AccountInfoDTO;
import pe.com.itworth.ttsclient.shared.FolderInfoDTO;
import pe.com.itworth.ttsclient.shared.MailDTO;


import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class MailboxController extends ListActivity {

	private Collection<MailDTO> mails;
	private MailManager mailManager;

	// private ProgressDialog progressDialog;
	private ReadingMessageDialog readingMessageDialog;

	private TextView stateBarTextView;
	private static String STATE = "";

	private Button stopReadingMessageButton;

	private MailDTOAdapter mailDTOAdapter;

	private FolderInfoDTO folder;
	private AccountInfoDTO account;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mailbox);

		Bundle b = getIntent().getExtras();
		if (b != null) {
			Parser parser = new ParserGSON();
			folder = (FolderInfoDTO) parser.aObjeto(b.getString("folder"),
					FolderInfoDTO.class);
			account = (AccountInfoDTO) parser.aObjeto(b.getString("account"),
					AccountInfoDTO.class);
		}

		readingMessageDialog = new ReadingMessageDialog(this);
		stopReadingMessageButton = (Button) readingMessageDialog
				.findViewById(R.id.stopReadingMessageButton);

		stopReadingMessageButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				vOnStopReadingMessageButtonClicked();
			}
		});

		mails = new ArrayList<MailDTO>();
		mailDTOAdapter = new MailDTOAdapter(this, R.layout.row, mails);
		setListAdapter(this.mailDTOAdapter);

		Runnable retrievingDataRunnable = new Runnable() {
			@Override
			public void run() {
				vDownloadMails();
			}
		};

		Thread thread = new Thread(null, retrievingDataRunnable,
				"MagentoBackground");
		thread.start();

		// progressDialog = ProgressDialog.show(MailboxController.this,
		// "Please wait", "Retrieving data ...", true);

		stateBarTextView = (TextView) findViewById(R.id.stateBarTextView);
		stateBarTextView.setText("Loading...");
	}

	@Override
	public void onListItemClick(ListView parent, View v, int position, long id) {
		vOnListItemClicked(position);
	}

	private void vOnListItemClicked(int iPosition) {
		String sMessage = ((ArrayList<MailDTO>) mails).get(
				(mails.size() - 1) - iPosition).getsMessage();

		if (sMessage == null)
			sMessage = "Mail without content";

		vSay(sMessage);
	}

	private void vOnStopReadingMessageButtonClicked() {
		MailboxTabPanelController.tts.stop();
		readingMessageDialog.dismiss();
	}

	private void vPopulateMailList() {
		if (mails != null && mails.size() > 0) {
			mailDTOAdapter.notifyDataSetChanged();
			for (int i = (mails.size() - 1); i >= 0; i--)
				mailDTOAdapter.add(((ArrayList<MailDTO>) mails).get(i));
		}
	}

	private void vUpdateState() {
		stateBarTextView.setText(STATE);
	}

	private void vDownloadMails() {

		Runnable populateMailListAndDismissRunnable = new Runnable() {
			@Override
			public void run() {
				vPopulateMailList();
				// progressDialog.dismiss();
				vUpdateState();
			}
		};

		mailManager = new MailMannagerGMAILImpl(new AccountInfoDTO(null,
				account.getsHost(), account.getsUsername(),
				account.getsPassword(), account.getsProvider(),null,null),
				new MailReaderJavaMailImpl());

		try {
			mails = mailManager.downloadMails(folder);

			Integer iNumberOfMails = 0;
			if (mails != null)
				iNumberOfMails = mails.size();
			STATE = iNumberOfMails + " mails";

		} catch (NoSuchProviderException e) {
			STATE = "Not supported protocol";
			e.printStackTrace();
		} catch (MessagingException e) {
			STATE = "Failed connection";
			e.printStackTrace();
		}

		runOnUiThread(populateMailListAndDismissRunnable);
	}

	private void vSay(final String sMessage) {

		Runnable speaking = new Runnable() {
			@Override
			public void run() {
				MailboxTabPanelController.tts.speak(sMessage,
						TextToSpeech.QUEUE_FLUSH, null);

				while (MailboxTabPanelController.tts.isSpeaking()) {
					// Log.e("TTS", "IS SPEAKING");
				}

				Runnable dismissReadingMessageDialogRunnable = new Runnable() {
					@Override
					public void run() {
						readingMessageDialog.dismiss();
					}
				};

				runOnUiThread(dismissReadingMessageDialogRunnable);
			}
		};

		Thread thread = new Thread(null, speaking, "MagentoBackground");
		thread.start();

		readingMessageDialog.show();
	}

	private class MailDTOAdapter extends ArrayAdapter<MailDTO> {

		private Collection<MailDTO> items;

		public MailDTOAdapter(Context context, int iTextViewResourceId,
				Collection<MailDTO> items) {
			super(context, iTextViewResourceId, (ArrayList<MailDTO>) items);
			this.items = items;
			Log.i("MAILADAPTER:", " instanciated");
		}

		@Override
		public View getView(int iPosition, View convertView, ViewGroup parent) {
			View v = convertView;
			// Log.i("MAILADAPTER", "executing getView");
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.row, null);
				Log.i("MAILADAPTER", "view is null");
			}
			MailDTO o = ((ArrayList<MailDTO>) items).get(iPosition);
			if (o != null) {
				// Log.i("MAILADAPTER", "object is NOT null");
				TextView tt = (TextView) v.findViewById(R.id.topText);
				TextView bt = (TextView) v.findViewById(R.id.bottomText);
				if (tt != null) {
					tt.setText("Subject: " + o.getsSubject());
				}
				if (bt != null) {
					bt.setText("From: " + o.getsFrom());
				}
			} else {
				Log.i("MAILADAPTER", "object is NULL");
			}
			return v;
		}
	}

}
